package DataStructure.Queue;

/**
 * @Author by KoVaVo
 * @Date 2021-05-11 19:24
 * @Desc: 手写队列
 * 实现方式：基于简单循环数组方式实现队列
 */
public class ArrayQueueDemo {
    //对首
    private int front;
    //队尾
    private int rear;
    private int capacity;

    private int [] array;

    private ArrayQueueDemo(int size){
        capacity = size;
        front =-1;
        rear = -1;
        array = new int[size];
    }

    public static ArrayQueueDemo createQueue(int size){
        return new ArrayQueueDemo(size);
    }

    public boolean isEmpty(){
        return (front == -1);
    }

    public boolean isFull(){
        return ((rear+1)%capacity == front);
    }

    public int getQueueSize(){
        return ((capacity-front+rear+1)%capacity);
    }

    public void enQueue(int data){
        if(isFull()){
            //可以抛出异常
            System.out.println("queue overflow");
        }else {
            rear=rear+1%capacity;
            array[rear] = data;
            if(front == -1){
                front = rear;
            }
        }
    }

    public int deQueue(){
        int data = 0;
        if(isEmpty()){
            //如果队列是空的，那么抛出异常
            System.out.println("queue is empty");
        }else {
            data = array[front];
            if(front == rear){
                front = rear-1;
            }else {
                front = (front + 1)%capacity;
            }
        }
        return data;
    }

}
